<!DOCTYPE html>
<html>

<head>
    <title>WebAssembly</title>
    <script src="test.js">
    </script>
</head>

<body>
    <h1>WebAssembly</h1>
    <img src="loading.gif" style="margin-top:10px" id="anim-loading">
    <br>
    <input type="number" id="int1" name="int1" value="0" />
    <input type="number" id="int2" name="int2" value="0" />
    <input type="button" value="Scan" onclick="add();" />
    <div id='result'></div>
    <canvas id='image' width='640' height='640'></canvas>

    <script type="text/javascript">
        var wa_add, wa_create, was_destroy, wasm;

        function add() {
            let int1 = document.getElementById('int1').value;
            let int2 = document.getElementById('int2').value;
            if (wa_add) {
                document.getElementById('result').innerText = wa_add(parseInt(int1), parseInt(int2));

                // API test
                if (wa_create && was_destroy) {

                    let canvas = document.getElementById('image');
                    var ctx = canvas.getContext('2d');
                    var image = ctx.getImageData(0, 0, canvas.width, canvas.height);
                    const p = wa_create(canvas.width, canvas.height);
                    wasm.HEAP8.set(image.data, p);
                    // Do something for the image buffer.
                    was_destroy(p);
                }


            } else {
                document.getElementById('result').innerText = parseInt(int1) + parseInt(int2);
            }
        }

        if (Module) {
            wasm = Module({
                wasmBinaryFile: 'test.wasm'
            });
            wasm.onRuntimeInitialized = function () {
                document.getElementById('anim-loading').style.display = 'none';
                wa_add = wasm._add;
                wa_create = wasm._create;
                was_destroy = wasm._destroy;
            };
        }
    </script>
</body>

</html>